import 'package:dio/dio.dart' as dio;
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../services/dio_service.dart';
import '../services/points_permission_service.dart';
import '../services/user_service.dart';
import '../models/index.dart';
import '../utils/encryption_util.dart';

/// 活动API调用类
/// 
/// 负责所有活动相关的API调用
/// 使用DioService进行网络请求，返回标准化的响应
class ActivityApi {
  // 🔗 API路径常量
  static const String nearbyActivitiesPath = '/activities/nearby/';
  static const String activityDetailPath = '/query/activity_user/';
  static const String publishActivityPath = '/activities/';
  static const String joinActivityPath = '/activities/participants/';
  
  // 📡 网络服务实例
  static DioService get _dioService => Get.find<DioService>();
  
  /// 获取附近的活动列表（使用AES加密）
  /// 
  /// 接口: POST /activities/nearby/
  /// 加密方式: AES-256-CBC
  /// 
  /// [latitude] 纬度
  /// [longitude] 经度
  /// [radius] 搜索半径（公里），默认50
  /// [limit] 返回数量限制，默认20
  /// [page] 页码，默认1
  /// [sortBy] 排序方式：'distance'(距离), 'time'(时间), 'distance_time'(综合)，默认'distance_time'
  /// [order] 排序顺序：'asc'(升序), 'desc'(降序)，默认'asc'
  /// 
  /// 返回活动列表响应
  static Future<ActivityListResp> getNearbyActivities({
    required double latitude,
    required double longitude,
    double radius = 50.0,
    int limit = 20,
    int page = 1,
    String sortBy = 'distance_time',
    String order = 'asc',
  }) async {
    try {
      debugPrint('🎯 =============== 获取附近活动 ===============');
      debugPrint('📍 纬度: $latitude');
      debugPrint('📍 经度: $longitude');
      debugPrint('📏 搜索半径: $radius km');
      debugPrint('🔢 数量限制: $limit');
      debugPrint('📄 页码: $page');
      debugPrint('🔄 排序方式: $sortBy');
      debugPrint('📊 排序顺序: $order');
      
      // 构建请求数据（不包含timestamp，会在加密时自动添加）
      final requestData = {
        'latitude': latitude,
        'longitude': longitude,
        'radius': radius,
        'limit': limit,
        'page': page,
        'sort_by': sortBy,
        'order': order,
      };
      
      debugPrint('📦 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      debugPrint('🔐 加密载荷已生成');
      debugPrint('🚀 发送加密请求到: $nearbyActivitiesPath');
      
      // 使用普通 post 方法（已加密）
      final response = await _dioService.post(
        nearbyActivitiesPath,
        data: encryptedPayload,
      );
      
      debugPrint('✅ 活动列表响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        // 检查响应状态
        if (responseData['status'] == 'success') {
          final result = ActivityListResp.fromJson(responseData);
          
          debugPrint('✅ 活动列表获取成功');
          debugPrint('📊 总数: ${result.activities.length}');
          debugPrint('📄 分页信息: ${result.pagination}');
          debugPrint('🔄 排序方式: $sortBy ($order)');
          
          // 打印前5个活动信息
          if (result.activities.isNotEmpty) {
            debugPrint('📋 前5个活动:');
            for (var i = 0; i < result.activities.length && i < 5; i++) {
              final activity = result.activities[i];
              debugPrint('   ${i + 1}. ${activity.activityTitle} - ${activity.distanceText}');
            }
          }
          
          return result;
        } else {
          final errorMsg = responseData['message'] ?? '活动列表获取失败';
          debugPrint('❌ 活动列表获取失败: $errorMsg');
          throw Exception(errorMsg);
        }
      } else {
        debugPrint('❌ 响应数据格式错误');
        throw Exception('服务器响应格式错误');
      }
    } on dio.DioException catch (e) {
      debugPrint('❌ 网络请求失败: ${e.message}');
      debugPrint('❌ 错误类型: ${e.type}');
      if (e.response != null) {
        debugPrint('❌ 响应状态码: ${e.response?.statusCode}');
        debugPrint('❌ 响应数据: ${e.response?.data}');
      }
      throw Exception('网络请求失败: ${e.message}');
    } catch (e, stackTrace) {
      debugPrint('❌ 获取活动列表失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      rethrow;
    }
  }
  
  /// 获取活动详情
  /// 
  /// [activityId] 活动ID
  /// 返回活动详情和发布者信息
  static Future<Map<String, dynamic>> getActivityDetail({
    required int activityId,
  }) async {
    try {
      debugPrint('🔍 =============== 获取活动详情 ===============');
      debugPrint('🆔 活动ID: $activityId');
      
      // 构建请求数据
      final requestData = {
        'activityId': activityId,
      };
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        activityDetailPath,
        data: encryptedPayload,
      );
      
      debugPrint('✅ 活动详情响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          debugPrint('✅ 活动详情获取成功');
          debugPrint('📊 活动信息: ${responseData['activity']}');
          debugPrint('👤 发布者信息: ${responseData['user']}');
          
          // 🔥 合并 user 信息到 activity（补充发布者积分等信息）
          if (responseData['activity'] != null && responseData['user'] != null) {
            final activity = responseData['activity'] as Map<String, dynamic>;
            final user = responseData['user'] as Map<String, dynamic>;
            
            // 补充发布者积分（从user.userPoints）
            if (user['userPoints'] != null && activity['publisherPoints'] == null) {
              activity['publisherPoints'] = user['userPoints'];
            }
            
            // 补充发布者性别（从user.userGender）
            if (user['userGender'] != null && activity['publisherGender'] == null) {
              activity['publisherGender'] = user['userGender'];
            }
            
            debugPrint('✅ 已合并用户信息到活动数据');
          }
          
          return responseData;
        } else {
          final errorMsg = responseData['message'] ?? '活动详情获取失败';
          debugPrint('❌ 活动详情获取失败: $errorMsg');
          throw Exception(errorMsg);
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 获取活动详情失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      rethrow;
    }
  }
  
  /// 加入活动
  /// 
  /// [activityId] 活动ID
  /// [userId] 用户ID
  /// [participantStatus] 参与者状态，默认'待审核'
  /// 返回加入结果
  static Future<Map<String, dynamic>> joinActivity({
    required int activityId,
    required int userId,
    String participantStatus = '待审核',
  }) async {
    try {
      debugPrint('🎯 =============== 加入活动 ===============');
      debugPrint('📝 活动ID: $activityId');
      debugPrint('👤 用户ID: $userId');
      debugPrint('📋 参与状态: $participantStatus');
      
      // 构建请求数据
      final requestData = {
        'activityId': activityId,
        'userId': userId,
        'participantStatus': participantStatus,
      };
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        joinActivityPath,
        data: encryptedPayload,
      );
      
      debugPrint('✅ 加入活动响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          debugPrint('✅ 加入活动成功');
          return responseData;
        } else {
          final errorMsg = responseData['message'] ?? '加入活动失败';
          debugPrint('❌ 加入活动失败: $errorMsg');
          throw Exception(errorMsg);
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 加入活动失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      rethrow;
    }
  }
  
  /// 🔥 发布活动（AES加密）
  /// 
  /// ✅ 修复：移除重复扣除积分的逻辑
  /// 积分扣除由后端根据free参数自动处理
  /// 
  /// [activityData] 活动数据Map（需要包含userId）
  /// [checkPermission] 是否检查积分权限（默认true）
  /// 返回发布结果
  static Future<Map<String, dynamic>> publishActivity({
    required Map<String, dynamic> activityData,
    bool checkPermission = true,
  }) async {
    try {
      debugPrint('📝 =============== 发布活动（AES加密） ===============');
      debugPrint('🎯 活动数据: $activityData');
      debugPrint('🎯 检查权限: $checkPermission');
      
      int free = 1;  // 默认免费
      int? userId;  // 用户ID
      
      // 获取用户ID
      if (activityData.containsKey('userId')) {
        userId = activityData['userId'] is int 
            ? activityData['userId'] 
            : int.tryParse(activityData['userId'].toString());
      }
      
      if (userId == null) {
        throw Exception('活动数据缺少用户ID（userId）');
      }
      
      debugPrint('👤 发布者ID: $userId');
      
      // 🔥 检查积分权限（如果启用）
      if (checkPermission) {
        try {
          final pointsPermissionService = Get.find<PointsPermissionService>();
          
          // 计算是否免费
          free = pointsPermissionService.calculatePublishActivityFree();
          
          debugPrint('💰 权限计算结果: ${free == 1 ? "免费" : "付费"}');
          
          // ✅ 如果需要付费，检查积分是否足够（不扣除，由后端处理）
          if (free == 0) {
            final cost = pointsPermissionService.publishActivityCost.value;
            final actualCost = cost == 0 ? 5 : cost;
            
            final userService = Get.find<UserService>();
            final currentPoints = userService.userInfo?.userPoints ?? 0;
            
            if (currentPoints < actualCost) {
              throw Exception('积分不足，发布活动需要${actualCost}积分');
            }
            
            debugPrint('💸 需要扣除积分: $actualCost（由后端处理）');
          }
        } catch (e) {
          debugPrint('❌ 积分权限检查失败: $e');
          // 积分不足或权限检查失败，直接抛出异常
          throw Exception('$e');
        }
      }
      
      // 🔥 添加free参数到活动数据
      final finalActivityData = Map<String, dynamic>.from(activityData);
      finalActivityData['free'] = free;
      
      debugPrint('📊 最终活动数据（含free参数）: $finalActivityData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(finalActivityData);
      
      // 发送请求
      final response = await _dioService.post(
        publishActivityPath,
        data: encryptedPayload,
      );
      
      debugPrint('✅ 发布活动响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          debugPrint('✅ 活动发布成功');
          
          // ✅ 根据后端返回的pointsChange更新本地积分
          final pointsChange = responseData['pointsChange'] ?? 0;
          if (pointsChange != 0) {
            try {
              final userService = Get.find<UserService>();
              final currentPoints = userService.userInfo?.userPoints ?? 0;
              final newPoints = currentPoints + (pointsChange is int ? pointsChange : (pointsChange as num).toInt());
              userService.updateUserPoints(newPoints);
              debugPrint('✅ 本地用户积分已更新: $currentPoints -> $newPoints (变化: $pointsChange)');
            } catch (e) {
              debugPrint('⚠️ 更新本地积分失败: $e');
            }
          }
          
          // 🔥 增加发布活动次数统计（如果启用权限检查）
          if (checkPermission) {
            try {
              final pointsPermissionService = Get.find<PointsPermissionService>();
              pointsPermissionService.incrementPublishActivityCount();
              debugPrint('✅ 发布活动次数统计已更新');
            } catch (e) {
              debugPrint('⚠️ 更新发布次数失败: $e');
            }
          }
          
          // 返回响应数据
          return {
            'status': 'success',
            'message': responseData['message'] ?? '活动发布成功',
            'activity_id': responseData['activity_id'],
            'pointsChange': pointsChange,  // ✅ 返回积分变化
          };
        } else {
          final errorMsg = responseData['message'] ?? '活动发布失败';
          debugPrint('❌ 活动发布失败: $errorMsg');
          throw Exception(errorMsg);
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 发布活动失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      rethrow;
    }
  }
  
  /// 举报活动（与小程序保持一致）
  /// 
  /// 接口: POST /reports/create/
  /// 加密方式: AES-256-CBC
  /// 
  /// [reporterId] 举报者ID
  /// [activityId] 活动ID
  /// [reportReason] 举报原因
  /// 返回举报结果
  static Future<Map<String, dynamic>> reportActivity({
    required int reporterId,
    required int activityId,
    required String reportReason,
  }) async {
    try {
      debugPrint('🚩 =============== 举报活动 ===============');
      debugPrint('👤 举报者ID: $reporterId');
      debugPrint('🎯 活动ID: $activityId');
      debugPrint('📝 举报原因: $reportReason');
      
      // 构建请求数据（与小程序保持一致）
      final requestData = {
        'reportType': '活动',  // 固定字符串 "活动"
        'reporterId': reporterId.toString(),  // 字符串格式的用户ID
        'contentId': activityId,  // 活动ID
        'reportReason': reportReason,  // 举报内容
      };
      
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        '/reports/create/',
        data: encryptedPayload,
      );
      
      debugPrint('✅ 举报响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          debugPrint('✅ 举报提交成功');
          return {
            'status': 'success',
            'message': responseData['message'] ?? '举报提交成功'
          };
        } else {
          debugPrint('❌ 举报提交失败: ${responseData['message']}');
          return {
            'status': 'error',
            'message': responseData['message'] ?? '举报失败'
          };
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 举报活动失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return {
        'status': 'error',
        'message': '举报提交失败: ${e.toString()}'
      };
    }
  }

  /// 获取发布者的活动参与者列表（使用AES加密）
  /// 
  /// 接口: POST /publisher/activity/participants
  /// 加密方式: AES-256-CBC
  /// 
  /// [publisherId] 发布者ID
  /// 返回发布者活动的所有参与者（待审核、已通过、已拒绝）
  static Future<PublisherParticipantsResp> getPublisherActivityParticipants({
    required int publisherId,
  }) async {
    try {
      debugPrint('👥 =============== 获取发布者活动参与者 ===============');
      debugPrint('👤 发布者ID: $publisherId');
      
      // 构建请求数据
      final requestData = {
        'userid': publisherId.toString(), // 使用userid参数名
      };
      
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        '/publisher/activity/participants',
        data: encryptedPayload,
      );
      
      debugPrint('✅ 参与者列表响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final participantsResponse = PublisherParticipantsResp.fromJson(responseData);
        
        if (participantsResponse.isSuccess) {
          debugPrint('✅ 参与者列表获取成功');
          debugPrint('📊 总数: ${participantsResponse.total}');
          debugPrint('⏳ 待审核: ${participantsResponse.pendingParticipants.length}');
          debugPrint('✅ 已通过: ${participantsResponse.approvedParticipants.length}');
          debugPrint('❌ 已拒绝: ${participantsResponse.rejectedParticipants.length}');
        } else {
          debugPrint('❌ 参与者列表获取失败: ${participantsResponse.message}');
        }
        
        return participantsResponse;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 获取参与者列表失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return PublisherParticipantsResp(
        status: 'error',
        message: '获取参与者列表失败: ${e.toString()}',
        participants: [],
        total: 0,
      );
    }
  }

  /// 审核活动参与者申请（使用AES加密）
  /// 
  /// 接口: POST /activities/participants/review
  /// 加密方式: AES-256-CBC
  /// 
  /// ⚠️ 重要：参考小程序实现
  /// - 审核状态必须使用中文：'通过'（同意）或'未通过'（拒绝）
  /// - 参数：activityId + userId（不是participantId）
  /// 
  /// [activityId] 活动ID
  /// [userId] 用户ID
  /// [reviewStatus] 审核状态：'通过'（同意）或'未通过'（拒绝）- 必须是中文！
  /// [reviewNote] 审核备注（可选）
  /// 返回审核结果
  static Future<ParticipantReviewResp> reviewParticipantApplication({
    required int activityId,
    required int userId,
    required String reviewStatus,
    String? reviewNote,
  }) async {
    try {
      debugPrint('✅ =============== 审核参与者申请 ===============');
      debugPrint('🎯 活动ID: $activityId');
      debugPrint('👤 用户ID: $userId');
      debugPrint('📝 审核状态: $reviewStatus');
      if (reviewNote != null) debugPrint('💬 审核备注: $reviewNote');
      
      // 🔥 构建请求数据（与小程序保持一致）
      final requestData = {
        'activityId': activityId,
        'userId': userId,
        'reviewStatus': reviewStatus,  // 必须是中文："通过" 或 "未通过"
        'timestamp': (DateTime.now().millisecondsSinceEpoch ~/ 1000),
      };
      
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        '/activities/participants/review',
        data: encryptedPayload,
      );
      
      debugPrint('✅ 审核响应: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final reviewResponse = ParticipantReviewResp.fromJson(responseData);
        
        if (reviewResponse.isSuccess) {
          debugPrint('✅ 审核成功: $reviewStatus');
        } else {
          debugPrint('❌ 审核失败: ${reviewResponse.message}');
        }
        
        return reviewResponse;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 审核参与者申请失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return ParticipantReviewResp(
        status: 'error',
        message: '审核失败: ${e.toString()}',
      );
    }
  }

  /// 编辑活动
  /// 
  /// 接口: POST /activities/edit
  /// 加密方式: AES-256-CBC
  /// 
  /// [activityId] 活动ID（必填）
  /// [activityTitle] 活动标题（可选）
  /// [activityDetails] 活动详情（可选）
  /// [activityLocation] 活动地点（可选）
  /// [activityImages] 活动图片（可选）
  /// [activityType] 活动类型（可选）
  /// [activityTags] 活动标签（可选）
  /// [activityMaxParticipants] 最大参与人数（可选）
  /// [activityPublishTime] 活动时间（可选）
  /// [latitude] 纬度（可选）
  /// [longitude] 经度（可选）
  /// [activityStatusMessage] 活动状态消息（可选）
  /// [extraData] 额外数据（可选）
  /// 返回编辑结果
  static Future<ActivityEditResp> editActivity({
    required int activityId,
    String? activityTitle,
    String? activityDetails,
    String? activityLocation,
    List<String>? activityImages,
    List<String>? activityType,
    List<String>? activityTags,
    int? activityMaxParticipants,
    String? activityPublishTime,
    double? latitude,
    double? longitude,
    String? activityStatusMessage,
    Map<String, dynamic>? extraData,
  }) async {
    try {
      debugPrint('✏️ =============== 编辑活动 ===============');
      debugPrint('🆔 活动ID: $activityId');
      if (activityTitle != null) debugPrint('📝 新标题: $activityTitle');

      // 创建请求模型
      final request = ActivityEditReq(
        activityId: activityId,
        activityTitle: activityTitle,
        activityDetails: activityDetails,
        activityLocation: activityLocation,
        activityImages: activityImages,
        activityType: activityType,
        activityTags: activityTags,
        activityMaxParticipants: activityMaxParticipants,
        activityPublishTime: activityPublishTime,
        latitude: latitude,
        longitude: longitude,
        activityStatusMessage: activityStatusMessage,
        extraData: extraData,
      );

      // 获取请求数据
      final requestData = request.toJson();
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        '/activities/edit',
        data: encryptedPayload,
      );

      debugPrint('✅ 活动编辑响应: ${response.statusCode}');

      // 解析响应
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final editResponse = ActivityEditResp.fromJson(responseData);

        if (editResponse.isSuccess) {
          debugPrint('✅ 活动编辑成功: ${editResponse.message}');
        } else {
          debugPrint('❌ 活动编辑失败: ${editResponse.message}');
        }

        return editResponse;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 编辑活动失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return ActivityEditResp(
        status: 'error',
        message: '编辑活动失败: ${e.toString()}',
      );
    }
  }

  /// 查询活动参与者
  /// 
  /// 接口: POST /activities/participants/edit
  /// 加密方式: AES-256-CBC
  /// 
  /// [activityId] 活动ID（必填）
  /// 返回活动参与者列表
  static Future<ActivityParticipantsResp> getActivityParticipants({
    required int activityId,
  }) async {
    try {
      debugPrint('👥 =============== 查询活动参与者 ===============');
      debugPrint('🆔 活动ID: $activityId');

      // 创建请求模型
      final request = ActivityParticipantsReq(
        activityId: activityId,
      );

      // 获取请求数据
      final requestData = request.toJson();
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送POST请求（加密）
      final response = await _dioService.post(
        '/activities/participants/edit',
        data: encryptedPayload,
      );

      debugPrint('✅ 活动参与者查询响应: ${response.statusCode}');

      // 解析响应
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final participantsResponse = ActivityParticipantsResp.fromJson(responseData);

        if (participantsResponse.isSuccess) {
          debugPrint('✅ 活动参与者查询成功');
          debugPrint('👥 参与者数量: ${participantsResponse.data?.total ?? 0}');
        } else {
          debugPrint('❌ 活动参与者查询失败: ${participantsResponse.message}');
        }

        return participantsResponse;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 查询活动参与者失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return ActivityParticipantsResp(
        status: 'error',
        message: '查询活动参与者失败: ${e.toString()}',
      );
    }
  }

  /// 删除活动参与者
  /// 
  /// 接口: POST /activities/participants/delete
  /// 加密方式: AES-256-CBC
  /// 
  /// [activityId] 活动ID（必填）
  /// [userId] 用户ID（必填）
  /// 返回删除结果
  static Future<DeleteParticipantResp> deleteActivityParticipant({
    required int activityId,
    required int userId,
  }) async {
    try {
      debugPrint('🗑️ =============== 删除活动参与者 ===============');
      debugPrint('🆔 活动ID: $activityId');
      debugPrint('👤 用户ID: $userId');

      // 创建请求模型
      final request = DeleteParticipantReq(
        activityId: activityId,
        userId: userId,
      );

      // 获取请求数据
      final requestData = request.toJson();
      debugPrint('📊 请求参数: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求
      final response = await _dioService.post(
        '/activities/participants/delete',
        data: encryptedPayload,
      );

      debugPrint('✅ 删除参与者响应: ${response.statusCode}');

      // 解析响应
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final deleteResponse = DeleteParticipantResp.fromJson(responseData);

        if (deleteResponse.isSuccess) {
          debugPrint('✅ 删除参与者成功: ${deleteResponse.message}');
        } else {
          debugPrint('❌ 删除参与者失败: ${deleteResponse.message}');
        }

        return deleteResponse;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 删除参与者失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return DeleteParticipantResp(
        status: 'error',
        message: '删除参与者失败: ${e.toString()}',
      );
    }
  }

  /// 删除活动（软删除）
  /// 
  /// 接口: POST /activities/edit
  /// 加密方式: AES-256-CBC
  /// 
  /// 通过修改 activityStatus 为 ["删除"] 来实现软删除
  /// 
  /// [activityId] 活动ID（必填）
  /// [userId] 用户ID（必填，用于权限验证）
  /// 返回删除结果
  static Future<Map<String, dynamic>> deleteActivity({
    required int activityId,
    required int userId,
  }) async {
    try {
      debugPrint('🗑️ =============== 删除活动（软删除） ===============');
      debugPrint('🆔 活动ID: $activityId');
      debugPrint('👤 用户ID: $userId');

      // 构建请求参数（通过设置状态为"删除"实现软删除）
      final requestData = <String, dynamic>{
        'activityId': activityId.toString(),
        'activityStatus': ['删除'], // 🎯 关键：设置状态为"删除"实现软删除
        'timestamp': (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString(),
      };

      debugPrint('📊 请求参数: $requestData');
      debugPrint('🎯 删除方式: 软删除（状态设置为"删除"）');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送请求到编辑接口（使用编辑接口来修改状态实现软删除）
      final response = await _dioService.post(
        '/activities/edit',
        data: encryptedPayload,
      );

      debugPrint('✅ 活动删除响应: ${response.statusCode}');

      // 检查响应状态
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          debugPrint('✅ 活动删除成功: ${responseData['message']}');
          return {
            'success': true,
            'status': 'success',
            'message': responseData['message'] ?? '活动已删除',
            'activityId': activityId,
          };
        } else {
          String errorMessage = '删除失败';
          if (responseData['message'] != null) {
            errorMessage = responseData['message'];
          }
          debugPrint('❌ 活动删除失败: $errorMessage');
          return {
            'success': false,
            'status': 'error',
            'message': errorMessage,
          };
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 删除活动失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return {
        'success': false,
        'status': 'error',
        'message': '删除活动失败: ${e.toString()}',
      };
    }
  }

  /// 获取用户内容（活动、评论、参与的活动）
  /// 
  /// 接口: POST /users/content/
  /// 加密方式: AES-256-CBC
  /// 
  /// 参考小程序实现：wanzhende-m/miniprogram/utils/api.js getUserContent
  /// 
  /// [userId] 用户ID（必填）
  /// [days] 查询天数（可选，默认30天）
  /// 返回用户内容数据
  static Future<Map<String, dynamic>> getUserContent({
    required int userId,
    int days = 30,
  }) async {
    try {
      debugPrint('📚 =============== 获取用户内容 ===============');
      debugPrint('👤 用户ID: $userId');
      debugPrint('📅 查询天数: $days');

      // 构建请求数据
      final requestData = {
        'userId': userId,
        'days': days,
        'timestamp': (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString(),
      };

      debugPrint('📊 请求参数: $requestData');

      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);

      // 发送请求
      final response = await _dioService.post(
        '/users/content/',
        data: encryptedPayload,
      );

      debugPrint('✅ 用户内容响应: ${response.statusCode}');

      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;

        debugPrint('📊 活动数量: ${(responseData['activities'] as List?)?.length ?? 0}');
        debugPrint('📊 已结束活动数量: ${(responseData['ended_activities'] as List?)?.length ?? 0}');
        debugPrint('📊 评论数量: ${(responseData['comments'] as List?)?.length ?? 0}');
        debugPrint('📊 参与活动数量: ${(responseData['participated_activities'] as List?)?.length ?? 0}');

        return responseData;
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 获取用户内容失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return {
        'status': 'error',
        'message': '获取用户内容失败: ${e.toString()}',
        'activities': [],
        'ended_activities': [],
        'comments': [],
        'participated_activities': [],
      };
    }
  }

  /// 🔥 获取用户历史记录
  /// 
  /// 参考小程序实现：wanzhende-m/miniprogram/utils/api.js getUserHistory
  /// 接口地址: POST /users/daily_activities_comments/
  /// 
  /// [userId] 用户ID
  /// [date] 查询日期 YYYY-MM-DD 格式
  /// [type] 查询类型（'all'=全部, 'activity'=活动, 'comment'=评论），默认'all'
  /// 返回历史记录列表
  static Future<UserHistoryResp> getUserHistory({
    required int userId,
    required String date,
    String type = 'all',
  }) async {
    try {
      debugPrint('📋 =============== 查询用户历史记录 ===============');
      debugPrint('👤 用户ID: $userId');
      debugPrint('📅 查询日期: $date');
      debugPrint('📝 查询类型: $type');
      
      // 构建请求数据
      final requestData = {
        'userId': userId,
        'date': date,
        'type': type,
      };
      
      debugPrint('📊 请求参数（加密前）: $requestData');
      
      // AES 加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      debugPrint('🔐 加密载荷已生成');
      debugPrint('🚀 准备发送加密请求到: /users/daily_activities_comments/');
      
      // 发送POST请求
      final response = await _dioService.post(
        '/users/daily_activities_comments/',
        data: encryptedPayload,
      );
      
      debugPrint('✅ 历史记录查询成功');
      debugPrint('📊 响应数据: ${response.data}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        
        if (responseData['status'] == 'success') {
          return UserHistoryResp.fromJson(responseData);
        } else {
          return UserHistoryResp.failure(
            responseData['message']?.toString() ?? '查询历史记录失败',
          );
        }
      } else {
        return UserHistoryResp.failure('服务器响应格式错误');
      }
    } catch (e, stackTrace) {
      debugPrint('❌ 查询历史记录失败: $e');
      debugPrint('📍 错误堆栈: $stackTrace');
      return UserHistoryResp.failure('查询历史记录异常：${e.toString()}');
    }
  }
}

